# Maintainer: Maksim Bondarenkov <maksapple2306@gmail.com>

_realname=turbo
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=2.5.3
pkgrel=1
pkgdesc="Incremental bundler and build system optimized for JavaScript and TypeScript (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://turbo.build'
msys2_repository_url='https://github.com/vercel/turborepo'
license=('spdx:MPL-2.0')
depends=("${MINGW_PACKAGE_PREFIX}-libgit2"
         "${MINGW_PACKAGE_PREFIX}-zlib"
         "${MINGW_PACKAGE_PREFIX}-zstd")
makedepends=("${MINGW_PACKAGE_PREFIX}-rust"
             "${MINGW_PACKAGE_PREFIX}-capnproto"
             "${MINGW_PACKAGE_PREFIX}-protobuf"
             "${MINGW_PACKAGE_PREFIX}-pkgconf"
             "${MINGW_PACKAGE_PREFIX}-openssl"
             "${MINGW_PACKAGE_PREFIX}-fontconfig"
             "${MINGW_PACKAGE_PREFIX}-freetype"
             'git')
options=('!strip')
source=("git+${msys2_repository_url}.git#tag=v${pkgver}"
        "zstd-sys.tar.gz::https://crates.io/api/v1/crates/zstd-sys/2.0.10+zstd.1.5.6/download"
        "zstd-sys-remove-statik.patch")
sha256sums=('a491e03bc773cee35ee51fecd49101c1ba7405e61c4474b0237286e233161357'
            'c253a4914af5bafc8fa8c86ee400827e83cf6ec01195ec1f1ed8441bf00d65aa'
            '48f4900ceb02d3aaf9a1020f33d56629156e96759f456c0e7ca18bfcf910767b')

prepare() {
  cd turborepo

  patch -d ../zstd-sys-2.0.10+zstd.1.5.6 -i ../zstd-sys-remove-statik.patch
  sed -i '/\[patch\.crates-io\]/a zstd-sys = { path = "../zstd-sys-2.0.10+zstd.1.5.6" }' Cargo.toml

  rm rust-toolchain.toml
  cargo update -p zstd-sys
  RUSTC_BOOTSTRAP=1 cargo fetch --locked --target "$(rustc -vV | sed -n 's/host: //p')"
}

build() {
  cd turborepo

  export RUSTC_BOOTSTRAP=1
  export OPENSSL_NO_VENDOR=1
  export LIBGIT2_NO_VENDOR=1
  export PKG_CONFIG_ALL_DYNAMIC=1
  export ZSTD_SYS_USE_PKG_CONFIG=1
  # this disables telemetry only at runtime, the relevant code is compiled anyway
  export TURBO_TELEMETRY_DISABLED=1
  cargo build --frozen --profile release-turborepo -p turbo
}

package() {
  install -Dm755 turborepo/target/release-turborepo/turbo "${pkgdir}${MINGW_PREFIX}/bin/turbo"

  local _complete='turborepo/target/release-turborepo/turbo completion'
  $_complete bash | install -Dm644 /dev/stdin "${pkgdir}${MINGW_PREFIX}/share/bash-completion/completions/${_realname}"
  $_complete fish | install -Dm644 /dev/stdin "${pkgdir}${MINGW_PREFIX}/share/fish/vendor_completions.d/${_realname}.fish"
  $_complete zsh | install -Dm644 /dev/stdin "${pkgdir}${MINGW_PREFIX}/share/zsh/site-functions/_${_realname}"

  install -Dm644 turborepo/LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
